import { Observable, filter, groupBy, map, max, mergeMap, shareReplay, take, toArray } from "rxjs"
import { ICellRaw } from "./util"

/**
 * 表格的行 映射成 对象
 */
export class RecordData
{
    index: number = 0
    rawData: IRecordCellRaw[] = []

    /**
     * 通过列数读取值
     * @param col 
     * @returns 
     */
    getCellByCol(col: number)
    {
        return this.rawData.find(v => v.col == col)
    }

    /**
     * 通过表头读取值
     * @param titleName 
     * @returns 
     */
    getCellByTitle(titleName: string)
    {
        return this.rawData.find(v => v.title == titleName)
    }

    /**
     * 生成一个对象(字典)
     * @returns 
     */
    toDict()
    {
        let dictObj: {[x:string]: string} = {}
        this.rawData.forEach(v => dictObj[v.title] = v.value)
        return dictObj
    }
}

/**
 * 创建RecordData对象
 * @param rowRawObs 
 * @param titleRawObs 
 * @returns 
 */
export function createRecordDataObs(rowRawObs: Observable<ICellRaw>, titleRawObs: Observable<ICellRaw>)
{
    titleRawObs = titleRawObs.pipe(shareReplay())
    let runObs = rowRawObs.pipe(
        groupBy(v => v.row),
        mergeMap(gObs => gObs.pipe(
            mergeMap(cell => titleRawObs.pipe(
                filter(titleCell => titleCell.col == cell.col),
                max(titleCell => titleCell.row),
                map(titleCell => ({
                    title: titleCell.value,
                    value: cell.value,
                    col: cell.col,
                    row: cell.row,
                    address: cell.address
                } satisfies IRecordCellRaw))
            )),
            toArray(),
            map(recordCellList =>
            {
                let rd = new RecordData()
                rd.index = gObs.key
                rd.rawData = recordCellList
                return rd
            })
        ))
    )
    return runObs
}

export interface IRecordCellRaw extends ICellRaw
{
    title: string
}